package com.app.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * EasyExcel读取数据为Map
 *
 * @author ch
 * @date 2023/1/12 14:27
 */
public class BaseDataExcelImportListener extends AnalysisEventListener<Map<Integer, Object>> {

    public static final ConcurrentHashMap<String, Object> CACHE = new ConcurrentHashMap<>();

    /**
     * excel头信息
     */
    private Map<Integer, String> headMap;

    /**
     * excel读取的数据集合
     */
    private final List<HashMap<String, Object>> list = new ArrayList<>();

    /**
     * 读取excel头信息
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.headMap = headMap;
    }

    /**
     * 读取数据为Map<Integer, Object>，需根据表头信息将其转换为map<表头,数据>
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context analysis context
     */
    @Override
    public void invoke(Map<Integer, Object> data, AnalysisContext context) {
        HashMap<String, Object> dataInfo = new HashMap<>(16);
        for (Integer key : data.keySet()) {
            dataInfo.put(headMap.get(key), data.get(key));
        }
        list.add(dataInfo);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        list.forEach(System.out::println);
        CACHE.put("data", list);
    }
}
